package com.zhangdy.agent.common.utils;

import com.zhangdy.agent.common.controller.AgentController;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.OperationsException;
import java.io.IOException;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

public class HotSwapClient {
    private static Logger logger = LoggerFactory.getLogger(HotSwapClient.class);

    private static Instrumentation instrumentation;

    public static void setInstrumentation(Instrumentation instrumentation) {
        HotSwapClient.instrumentation = instrumentation;
    }

    public static void redefine(Class<?> oldClass, CtClass newClass) {
        try {
            ClassDefinition def = new ClassDefinition(oldClass, newClass.toBytecode());
            instrumentation.redefineClasses(def);
        }catch (Exception e) {
            logger.error("", e);
            throw new RuntimeException();
        }

    }
    public static void redefine(CtClass newClasses) {
        try {
            ClassDefinition def = new ClassDefinition(Class.forName(newClasses.getName()), newClasses.toBytecode());
            instrumentation.redefineClasses(def);
        }catch (Exception e) {
            logger.error("", e);
            throw new RuntimeException();
        }

    }
}
